import { Image, View } from "@tarojs/components";
import UserAvatar from "@/components/user/user-avatar";
import { useAppDispatch, useAppSelector } from "@/hook";
import Taro from "@tarojs/taro";
import {
  checkRoles,
  getUserInfo,
  selectUserInfo,
} from "@/features/user/userSlice";
import orderIcon from "@/assets/icons/order.png";
import editIcon from "@/assets/icons/edit.png";
import addressIcon from "@/assets/icons/location.png";
import mountedIcon from "@/assets/icons/mounted.png";
import walletIcon from "@/assets/icons/wallet.png";

import { WalletPackageDto } from "@/apis/__generated/model/dto";
import { useImmer } from "use-immer";
import { api } from "@/utils/api-instance";
import coinBackground from "@/assets/images/coin-background.png";
import { switchPage } from "@/utils/common";
import RegisterPopup from "@/components/register-popup";
import "./user.scss";

export default function User() {
  const dispatch = useAppDispatch();
  Taro.showShareMenu({
    withShareTicket: true,
    showShareItems: ["shareAppMessage", "shareTimeline"],
  });
  const userInfo = useAppSelector(selectUserInfo);
  const handleEdit = () => {
    Taro.navigateTo({
      url: "./user-edit",
    });
  };
  const [packages, setPackages] = useImmer<
    WalletPackageDto["WalletPackageRepository/COMPLEX_FETCHER_FOR_FRONT"][]
  >([]);
  Taro.useLoad(async () => {
    const list = (
      await api.walletPackageForFrontController.query({
        body: {
          query: {},
          pageSize: 10,
          pageNum: 1,
          sorts: [{ property: "price", direction: "ASC" }],
        },
      })
    ).content;
    setPackages([...list]);
    dispatch(getUserInfo());
  });
  const handleWalletPackagePay = async (
    pack: WalletPackageDto["WalletPackageRepository/COMPLEX_FETCHER_FOR_FRONT"],
  ) => {
    const res = await Taro.showModal({
      title: pack.name,
      content: "是否购买套餐？",
      confirmText: "购买",
      cancelText: "取消",
    });
    if (res.cancel) return;
    Taro.showLoading();
    const payRest = await api.walletOrderForFrontController.save({
      body: {
        walletPackageId: pack.id,
      },
    });
    Taro.requestPayment({
      nonceStr: payRest.nonceStr,
      package: payRest.packageValue,
      paySign: payRest.paySign,
      timeStamp: payRest.timeStamp,
      signType: payRest.signType as "RSA",
      success: () => {
        Taro.showLoading();
        Taro.showToast({
          title: "支付成功",
          icon: "success",
        });
        dispatch(getUserInfo());
      },
      fail: (failRes) => {
        Taro.showLoading();
        Taro.showToast({ title: failRes.errMsg, icon: "none" });
      },
    });
  };
  const hasRole = useAppSelector((state) => checkRoles(state, ["接单者"]));
  return (
    <View className="user-page">
      <Image
        className="background"
        mode="aspectFill"
        src="https://my-resource-share.oss-cn-qingdao.aliyuncs.com/config/BJ.jpg"
      ></Image>
      <View className="user-wrapper">
        <View className="user-section">
          <View className="user-info" onClick={() => handleEdit()}>
            <UserAvatar
              src={userInfo?.avatar}
              radius="50%"
              width="100rpx"
              height="100rpx"
            ></UserAvatar>
            <View className="username">
              {userInfo ? (
                <View className="name">{userInfo.nickname}</View>
              ) : (
                <View
                  className="name not-login"
                  onClick={(event) => {
                    event.stopPropagation();
                    dispatch(getUserInfo());
                  }}
                >
                  您还未登录,点击登录
                </View>
              )}
            </View>
          </View>
        </View>
      </View>
      <View className="divider">
        <View className="front">我的钱包</View>
        <View className="rear">MY Wallet</View>
      </View>

      <View
        className="wallet"
        onClick={() => switchPage("/pages/user/wallet-record")}
      >
        <View className="balance">
          <Image
            className="coin-background"
            src={coinBackground}
            mode="aspectFill"
          />
          <View className="title">钱包剩余</View>
          <View className="value">{userInfo?.wallet?.balance || 0}</View>
        </View>
        <View className="packages">
          {packages.map((item) => {
            return (
              <View
                className="package"
                key={item.name}
                onClick={() => handleWalletPackagePay(item)}
              >
                <View className="name">{item.name}</View>
                <View className="price">￥{item.price}</View>
              </View>
            );
          })}
        </View>
      </View>
      <View className="divider">
        <View className="front">个人中心</View>
        <View className="rear">MY SERVICE</View>
      </View>
      <View className="functions">
        <View
          className="function"
          onClick={() => switchPage("/pages/index/order-list")}
        >
          <Image src={orderIcon} mode="widthFix" className="icon" />
          <View className="name">我的订单</View>
        </View>
        {hasRole ? (
          <View
            className="function"
            onClick={() => switchPage("/pages/index/deliver-order-list")}
          >
            <Image src={mountedIcon} mode="widthFix" className="icon" />
            <View className="name">接单大厅</View>
          </View>
        ) : (
          <View
            className="function"
            onClick={() => switchPage("/pages/index/deliver-register")}
          >
            <Image src={mountedIcon} mode="widthFix" className="icon" />
            <View className="name">注册骑手</View>
          </View>
        )}

        <View
          className="function"
          onClick={() => switchPage("../address/address-list")}
        >
          <Image src={addressIcon} mode="widthFix" className="icon" />
          <View className="name">地址簿</View>
        </View>
        <View
          className="function"
          onClick={() => switchPage("../wallet-record")}
        >
          <Image src={walletIcon} mode="widthFix" className="icon" />
          <View className="name">钱包记录</View>
        </View>
        <View
          className="function"
          onClick={() => switchPage("/pages/feedback/feedback")}
        >
          <Image src={editIcon} mode="widthFix" className="icon" />
          <View className="name">留言反馈</View>
        </View>
      </View>
      <RegisterPopup></RegisterPopup>
    </View>
  );
}
